package com.olympia.myapp.activity;

import java.util.List;
import java.util.Random;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.olympia.myapp.R;
import com.olympia.myapp.base.BaseActivity;
import com.olympia.myapp.custom.Dialog_Confirm;
import com.olympia.myapp.custom.Dialog_Confirm.ProcessDialogConfirm;
import com.olympia.myapp.entity.Member;
import com.olympia.myapp.entity.QuestionTT;
import com.olympia.myapp.server.HttpConnection;
import com.olympia.myapp.util.AnimationControl;
import com.olympia.myapp.util.Constants;
import com.olympia.myapp.util.ControlListener;
import com.olympia.myapp.util.Reminder;
import com.olympia.myapp.util.WaitingReminder;
import com.olympia.myapp.xml.QuestionXMLHandler;

public class TTActivity extends BaseActivity {
	TextView txtScore = null;
	TextView txtCount = null;
	Button btnA = null;
	Button btnB = null;
	Button btnC = null;
	Button btnD = null;
	Button btnCorrect = null;
	ImageView icRec = null;

	RelativeLayout layoutQuestion = null;
	RelativeLayout layoutAnswer = null;
	RelativeLayout layBar = null;

	TextView txtQuestionContent = null;
	TextView txtQuestionResult = null;
	// danh sách ng tra loi
	TextView txtName1 = null;
	TextView txtTime1 = null;
	TextView txtResult1 = null;

	TextView txtName2 = null;
	TextView txtTime2 = null;
	TextView txtResult2 = null;

	TextView txtName3 = null;
	TextView txtTime3 = null;
	TextView txtResult3 = null;

	TextView txtName4 = null;
	TextView txtTime4 = null;
	TextView txtResult4 = null;

	//
	List<QuestionTT> arrTTQuestion = null;
	QuestionTT questionCurr = null;
	int size = 4;
	int num = 0;
	int timeAnswer = 0;
	int timeCount = 0;
	int timeMax = 30;
	String contentAnswer = "";
	// dialog confirm
	Dialog_Confirm dg_confirm = null;
	WaitingReminder waitingControl = null;
	int timeWaiting = 17 * 1000;
	int timeDelay = 5 * 1000;
	Reminder remind = null;
	AnimationControl animateControl = null;
	// các thông số dùng để vẽ đồng hồ
	int barH = 100;
	int top = 0;
	int topOld = 0;
	int percel = 5;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ttactivity);
		intent = getIntent();

		num = 0;
		animateControl = new AnimationControl();
		// khơi tạo
		txtScore = (TextView) findViewById(R.id.tt_layout_right_score);
		txtCount = (TextView) findViewById(R.id.tt_layout_right_num);
		updateScoreAndNum();
		icRec = (ImageView) findViewById(R.id.tt_layout_right_rec);
		// button
		btnA = (Button) findViewById(R.id.tt_layout_question_btnA);
		btnA.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnA.setFocusableInTouchMode(true);
				clickAnswer();
				return false;
			}
		});
		btnB = (Button) findViewById(R.id.tt_layout_question_btnB);
		btnB.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnB.setFocusableInTouchMode(true);
				clickAnswer();
				return false;
			}
		});
		btnC = (Button) findViewById(R.id.tt_layout_question_btnC);
		btnC.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnC.setFocusableInTouchMode(true);
				clickAnswer();
				return false;
			}
		});
		btnD = (Button) findViewById(R.id.tt_layout_question_btnD);
		btnD.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				clearFocus();
				btnD.setFocusableInTouchMode(true);
				clickAnswer();
				return false;
			}
		});
		clearFocus();
		btnCorrect = (Button) findViewById(R.id.tt_layout_answer_btnCorrect);
		// layout
		layBar = (RelativeLayout) findViewById(R.id.tt_layout_right_bar2);
		layoutQuestion = (RelativeLayout) findViewById(R.id.tt_layout_question);
		layoutAnswer = (RelativeLayout) findViewById(R.id.tt_layout_answer);
		layoutQuestion.setVisibility(View.GONE);
		layoutAnswer.setVisibility(View.GONE);
		// nguoi choi
		txtName1 = (TextView) findViewById(R.id.tt_layout_answer1_name);
		txtTime1 = (TextView) findViewById(R.id.tt_layout_answer1_time);
		txtResult1 = (TextView) findViewById(R.id.tt_layout_answer1_result);

		txtName2 = (TextView) findViewById(R.id.tt_layout_answer2_name);
		txtTime2 = (TextView) findViewById(R.id.tt_layout_answer2_time);
		txtResult2 = (TextView) findViewById(R.id.tt_layout_answer2_result);

		txtName3 = (TextView) findViewById(R.id.tt_layout_answer3_name);
		txtTime3 = (TextView) findViewById(R.id.tt_layout_answer3_time);
		txtResult3 = (TextView) findViewById(R.id.tt_layout_answer3_result);

		txtName4 = (TextView) findViewById(R.id.tt_layout_answer4_name);
		txtTime4 = (TextView) findViewById(R.id.tt_layout_answer4_time);
		txtResult4 = (TextView) findViewById(R.id.tt_layout_answer4_result);

		//
		txtQuestionContent = (TextView) findViewById(R.id.tt_layout_question_main_content);
		txtQuestionResult = (TextView) findViewById(R.id.tt_layout_question_main_result);
		// nap dữ liệu
		if (QuestionXMLHandler.qsTT != null) {
			arrTTQuestion = QuestionXMLHandler.qsTT;
			size = arrTTQuestion.size();
		}
		// phát âm thanh
		Constants.myService.playTT();
		// hiển thị dialog thông báo vào chơi phần thi tưng tốc
		showDialogConfirm(0, getString(R.string.note_title),
				"PHẦN THI TĂNG TỐC.");
		waitingControl = new WaitingReminder(new ControlListener() {
			public void runTask() {
				// stop âm thanh begin
				if (num == 0)
					Constants.myService.playTTBegin();
				// bắt đầu load câu hỏi
				loadQuestion();
				// tat dialog
				if (dg_confirm.isShowing()) {
					dg_confirm.dismiss();

					barH = layBar.getHeight() + icRec.getHeight();
					top = topOld = 0;
					percel = barH / timeMax;
					if (percel <= 0) {
						if (DENSITY == 120) {
							percel = 3;
						} else if (DENSITY == 160) {
							percel = 4;
						} else if (DENSITY == 240) {
							percel = 6;
						} else if (DENSITY == 320) {
							percel = 8;
						} else
							percel = 4;
					}
				}
			}
		});
		waitingControl.start(timeWaiting);

		// khai báo control timer
		remind = new Reminder(new ControlListener() {
			public void runTask() {
				// cập nhật thời gian
				timeCount--;

				top += percel;
				layBar.setPadding(0, top, 0, 0);
			}

			public void stopTask() {
				top = topOld;
				layBar.setPadding(0, top, 0, 0);
				loadAnswer();
			}
		}, timeMax);

	}

	/**
	 * ẩn hiện layout theo trình tự
	 */
	private void showlayoutQuestion(boolean isShow) {
		if (layoutQuestion != null && layoutAnswer != null) {
			if (isShow) {
				layoutQuestion.setVisibility(View.VISIBLE);
				layoutAnswer.setVisibility(View.GONE);
				animateControl.RunAnimations(this, layoutQuestion,
						R.anim.slide_right);
			} else {
				layoutQuestion.setVisibility(View.GONE);
				layoutAnswer.setVisibility(View.VISIBLE);
				animateControl.RunAnimations(this, layoutAnswer,
						R.anim.tranlate);
			}
		}
	}

	/**
	 * hien thi dialog xác nhận
	 * 
	 * @param typeDg
	 * @param title
	 * @param content
	 */
	private void showDialogConfirm(int typeDg, String title, String content) {
		if (!this.isFinishing()) {
			dg_confirm = new Dialog_Confirm(this, title, content, false,
					typeDg == 0 ? false : true, new ProcessDialogConfirm() {
						@Override
						public void click_Ok() {
						}

						@Override
						public void click_Cancel() {
						}
					});

			dg_confirm.setContent(content);
			dg_confirm.setCancelable(false);
			dg_confirm.show();
		}
	}

	private void showDialogAcceptScore(String title, String content) {
		if (!this.isFinishing()) {
			Dialog_Confirm dgconfirm = new Dialog_Confirm(this, title, content,
					false, true, new ProcessDialogConfirm() {
						@Override
						public void click_Ok() {
						}

						@Override
						public void click_Cancel() {
							// gui yeu cầu xác nhận điểm lên sẻver
							acceptScore();
						}
					});

			dgconfirm.setTextOnButton("", "Tiếp tục");
			dgconfirm.setCancelable(false);

			dgconfirm.show();
		}
	}

	/**
	 * hiển thị nội dung câu hỏi
	 */
	private void loadQuestion() {
		clearFocus();
		// cập nhật lại
		timeAnswer = 30;
		timeCount = timeMax = 30;
		contentAnswer = "";

		if (num < size) {
			showlayoutQuestion(true);
			questionCurr = arrTTQuestion.get(num);
			if (questionCurr != null) {
				txtQuestionContent.setText(questionCurr.content);
				txtQuestionResult.setText(questionCurr.answerContent);

				animateControl.RunAnimations(this, txtQuestionContent,
						R.anim.alpha);
				animateControl.RunAnimations(this, txtQuestionResult,
						R.anim.alpha);

			}
			num++;
			// update score and num
			updateScoreAndNum();
			remind.resetTime(timeMax);
			remind.start(1);

			Constants.myService.playTT30();
		} else {
			layoutAnswer.setVisibility(View.GONE);
			layoutQuestion.setVisibility(View.GONE);
			// hiển thị dilog hoàn thành phần TT
			String str = String.format(
					getResources().getString(R.string.start_content_score),
					"TĂNG TỐC", Constants.SCORE);
			showDialogAcceptScore(getString(R.string.note_title), str);
		}
	}

	/**
	 * load câu trả lời
	 */
	private void loadAnswer() {
		showlayoutQuestion(false);
		List<Member> lstMember = questionCurr.member;
		Member m = null;
		if (lstMember != null) {
			// sắp xếp
			m = new Member();
			m.name = Constants.myAccount.name;
			m.ansTime = String.valueOf(timeAnswer);
			m.ansContet = contentAnswer;
			lstMember.add(m);
			//
			if (lstMember.size() >= 2) {
				lstMember = sortMember(lstMember);
			}
			// lấy vị trí của ng trả lơi đúng
			idAns = 0;
			for (int i = 0; i < lstMember.size(); i++) {
				Member mem = lstMember.get(i);
				if (mem.ansContet.toUpperCase().compareTo(
						contentAnswer.toUpperCase()) == 0) {
					idAns++;
					if (mem.name.compareTo(m.name) == 0) {
						break;
					}
				}
			}

			for (int i = 0; i < lstMember.size(); i++) {
				m = lstMember.get(i);
				if (m != null) {
					if (i == 0) {
						txtName1.setText(m.name);
						txtResult1.setText(m.ansContet);
						txtTime1.setText(m.ansTime);
					}
					if (i == 1) {
						txtName2.setText(m.name);
						txtResult2.setText(m.ansContet);
						txtTime2.setText(m.ansTime);
					}
					if (i == 2) {
						txtName3.setText(m.name);
						txtResult3.setText(m.ansContet);
						txtTime3.setText(m.ansTime);
					}
					if (i == 3) {
						txtName4.setText(m.name);
						txtResult4.setText(m.ansContet);
						txtTime4.setText(m.ansTime);
					}
				}
			}
		}
		btnCorrect.setText(questionCurr.answer);
		// kiem tra câu trả lời
		if (checkAnswer()) {
			// phat am thanh dung
			if (!isFinishing()) {
				int ran = (new Random()).nextInt(100) % 2;
				if (ran == 0)
					Constants.myService.playCorrect1();
				else
					Constants.myService.playCorrect2();
			}
		} else {
			// phat am thanh sai
			if (!isFinishing())
				Constants.myService.playUnCorrect2();
		}
		waitingControl.start(timeDelay);
	}

	/**
	 * sắp xếp thời gian trả lời
	 * 
	 * @param lst
	 */
	private List<Member> sortMember(List<Member> lst) {
		try {
			Member mi = null;
			Member mj = null;
			for (int i = 0; i < lst.size() - 1; i++) {
				mi = lst.get(i);
				for (int j = i + 1; j < lst.size(); j++) {
					mj = lst.get(j);

					if (mi != null && mj != null) {
						int ti = Integer.parseInt(mi.ansTime);
						int tj = Integer.parseInt(mj.ansTime);
						if (ti > tj) {
							lst.set(j, mi);
							lst.set(i, mj);
						}
					}
					if (mi == null)
						lst.remove(i);

					if (mj == null)
						lst.remove(j);
				}
			}
		} catch (Exception e) {
		}

		return lst;
	}

	/**
	 * cập nhật lại điểm và câu trả lời
	 */
	private void updateScoreAndNum() {
		if (txtCount != null && txtScore != null) {
			txtCount.setText(String.valueOf(num));
			txtScore.setText(String.valueOf(Constants.SCORE));
		}
	}

	/**
	 * chọn câu trả lời
	 */
	private void clickAnswer() {
		timeAnswer = timeMax - timeCount;
		switch (checkBtnFocus()) {
		case 1:
			contentAnswer = "A";
			break;
		case 2:
			contentAnswer = "B";
			break;
		case 3:
			contentAnswer = "C";
			break;
		case 4:
			contentAnswer = "D";
			break;
		default:
			timeAnswer = timeMax;
			contentAnswer = "";
			break;
		}
	}

	/**
	 * trạng thái active
	 * 
	 * @param index
	 */
	private void clearFocus() {
		btnA.setFocusableInTouchMode(false);
		btnB.setFocusableInTouchMode(false);
		btnC.setFocusableInTouchMode(false);
		btnD.setFocusableInTouchMode(false);
	}

	/**
	 * kiem tra chon button nao
	 * 
	 * @return
	 */
	private int checkBtnFocus() {
		int idFocus = 0;
		if (btnA.isFocusableInTouchMode())
			idFocus = 1;
		else if (btnB.isFocusableInTouchMode())
			idFocus = 2;
		else if (btnC.isFocusableInTouchMode())
			idFocus = 3;
		else if (btnD.isFocusableInTouchMode())
			idFocus = 4;
		return idFocus;
	}

	/**
	 * kiểm tra câu trả lời có đúng không
	 * 
	 * @return
	 */
	int idAns = 1;

	private boolean checkAnswer() {
		if (questionCurr.answer.toUpperCase().equals(
				contentAnswer.toUpperCase())) {
			int p = (idAns == 1 ? 40 : idAns == 2 ? 30 : idAns == 3 ? 20 : 10);
			Constants.SCORE += p;
			updateScoreAndNum();
			return true;
		}
		return false;
	}

	/**
	 * =================== gui yeu cau xac nhan diem len server
	 * ===================
	 */
	private void acceptScore() {
		String urlScore = urlUtil.acceptScore(Constants.myAccount.mail,
				String.valueOf(Constants.SCORE));
		requestServer(urlScore);
	}

	public void requestServer(String url) {
		if (!isRequest) {
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message message) {
					switch (message.what) {
					case HttpConnection.DID_START: {
						break;
					}
					case HttpConnection.DID_SUCCEED: {
						// String result = message.obj.toString();
						intent = new Intent(TTActivity.this, VDActivity.class);
						startActivity(intent);
						overridePendingTransition(R.anim.fase_in,
								R.anim.fade_out);
						finish();
						break;
					}
					case HttpConnection.DID_ERROR: {
						msgUtil.showToast(TTActivity.this,
								getString(R.string.error_connect));
						break;
					}
					}
				}
			};

			new HttpConnection(handler).get(url);
		}
	}

	@Override
	public void onBackPressed() {
		//Constants.myService.clearAll();
		super.onBackPressed();
	}
}
